package org.jaaksi.kottlindemo.test

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import extension.addFragment
import kotlinx.android.synthetic.main.activity_test_fragment.*
import org.jaaksi.kottlindemo.R
import timber.log.Timber
import java.util.concurrent.locks.ReentrantLock

class TestSyncActivity : AppCompatActivity() {
    private var fragment2: TestAnimFragment2? = null
    private var hasData = false
    private val lock = ReentrantLock()
    private val task = TaskRunnable()

    private var hasWaveShow = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test_fragment)
//        fragment2 = addFragment(
//            supportFragmentManager,
//            android.R.id.content,
//            TestAnimFragment2::class.java
//        ) as TestAnimFragment2
//        addFragment(supportFragmentManager, R.id.fragment_container, TestFragment1::class.java)

        btnStart.setOnClickListener {
            task.start()
        }

        btnStop.setOnClickListener {
            Timber.i("stop")
            task.stop()
            lock.lock()
            Timber.i("main get lock")
            hasData = true
            Timber.i("main fix hasData = $hasData")
            lock.unlock()
        }

    }

    private inner class TaskRunnable : Runnable {
        private var thread: Thread? = null

        fun start() {
            if (thread == null) {
                hasWaveShow = false
                thread = Thread(this)
                thread!!.priority = 1
                thread!!.start()
            }
        }

        fun stop() {
            // 可能引起，本来hasWaveShow已经为true了，这里又置为false，导致线程执行的时候
            if (thread != null) {
                thread = null
                lock.lock()
                hasWaveShow = false
                lock.unlock()
            }
        }

        override fun run() {
            lock.lock()
            while (thread != null) {
                Timber.i("sleep 1000")
                Thread.sleep(2000)
                Timber.i("thread fix hasData = $hasData")
                hasData = false
                if (!hasWaveShow) {
                    hasWaveShow = true
                    Timber.i("has Wave Show")
                }
            }
            Timber.i("thread unlock")
            lock.unlock()
            Timber.i("thread unlock end")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }


}